import { NextFunction, Request, Response } from "express";
import { ArticleModel } from "../schema/Article.schema";
import { Error } from "mongoose";

export class ArticleController {
  async findAll(req: Request, res: Response, next: NextFunction) {
    try {
      // 获取分页参数，默认 page=1, pageSize=10
      const page = parseInt(req.query.page as string) || 1;
      const pageSize = parseInt(req.query.pageSize as string) || 20;

      // 计算偏移量
      const skip = (page - 1) * pageSize;
      const total = await ArticleModel.countDocuments();

      const articles = await ArticleModel.find()
        .skip(skip)
        .limit(pageSize)
        .sort({ createAt: -1 });
      res.status(200).send({
        total,
        page,
        pageSize,
        list: articles,
      });
    } catch (error) {
      next(error);
    }
  }

  async findOne(req: Request, res: Response, next: NextFunction) {
    try {
      const result = await ArticleModel.findById(req.params.id);
      if (!result) {
        next(new Error("Article not found"));
      } else {
        res.status(200).send(result);
      }
    } catch (error) {
      next(error);
    }
  }

  async create(req: Request, res: Response, next: NextFunction) {
    try {
      const result = await ArticleModel.create(req.body);
      res.status(201).send(result);
    } catch (error) {
      next(error);
    }
  }
}
